define(["angularAMD", "moment"], function (angularAMD, moment) {
    angularAMD.service('F0102Service', ['$rootScope', '$filter', '$translate', 'config', '$timeout', 'MMWService', '$mdDialog', '$calculater', '$interval', '$mddProvider',
        function ($rootScope, $filter, $translate, config, $timeout, $MMWService, $mdDialog, $calculater, $interval, $mddProvider) {
            /**
             * options : {
             *      wo_no: 工單編號
             *      op_no: 作業站編號
             *      machine_no: 設備編號
             *      materialItem: 勾選的物料
             *      callback : function
             * }
            **/
            this.init = function (options) {
                var material_type = ''; // 物料管理頁面的替代料類別
                var material_no = ''; // 物料管理頁面的替代料編號
                var barcode_format = '';
                var feed_content = undefined;//20210507 modify by 德義_林佳諺 for #0086310 設備grid參數
                if(options){
                    if(options.materialItem){
                        material_type = options.materialItem.substitute_material_type || '';
                        material_no = options.materialItem.substitute_material_no || '';
                        barcode_format = options.materialItem.barcode_format || '';
                        if(options.feed_content){
                            feed_content = options.feed_content
                        }
                    }
                }

                //上料條碼解析
                function barcodeAnalysis(barcode, callback){
                    var content = {
                        material_type: material_type,
                        material_no: material_no,
                        barcode_format: barcode_format,
                        barcode: barcode
                    };
                    feedingBarcodeAnalysisProcess(content, function(data){
                        if (data.material_plot_no && data.material_plot_no != ''){
                            if (callback)
                                callback(data.material_plot_no, data.product_date, data.Qty);
                        } else {
                            if (callback)
                                //20220905 modify by wangqq M#0118356：上料页面无法显示数量字段
                                callback('N/A',  data.product_date,data.Qty);
                            // $rootScope.showAlert($filter('translate')('F0102.msg.analysis_result_empty')); //回傳的解析結果為空白
                        }
                    });
                }

                //上料條碼解析作業
                function feedingBarcodeAnalysisProcess(content, callback){
                    // if (callback)
                    //     callback({material_plot_no: 'MO123456789'});
                    $MMWService.sendToServer({
                        uri: 'ServicesSTD.Module_MAT.feeding_barcode_analysis_process',
                        content : content,
                        success : function(data) {
                            if(data.Qty){//20210107 add by Oliver for M#84667;
                                if(data.Qty == ""){
                                    data.Qty = 0;
                                }
                            }else{
                                data.Qty = 0;
                            }
                            if (callback)
                                callback(data);
                        }
                    });
                }

                //上料前檢查
                function beforeFeeding(dialog, callback) {                    
                    var msg = '';
                    // if(dialog.material_plot_no == ''){
                    //     msg = $filter('translate')('F0102.msg.material_plot_no_empty');
                    // }else 
                    if(dialog.qty === ''){
                        msg = $filter('translate')('F0102.msg.qty_must_gt_zero');
                    }
                    
                    if (msg == ''){
                        if (callback)
                            callback();
                    } else {
                        $rootScope.showAlert(msg);
                    }
                }

                //上料作業
                function feedingProcess(content, callback){
                    // $rootScope.showToast('上料成功');
                    // if (callback)
                    //     callback();
                    $MMWService.sendToServer({
                        uri:'ServicesSTD.Module_MAT.feeding_process',
                        content : content,
                        success : function(data, response) {
                            $rootScope.showToast(response.Message);
                            if (callback)
                                callback(data);
                        }
                    });
                }
                //20210528 modify by 德義_林佳諺 for #0086310 : PlugIn == 5 時上料
                function dispatchfeedingProcess(content, callback){
                    $MMWService.sendToServer({
                        uri: 'ServicesSTD.Module_MAT.dispatch_feeding_process',
                        content:content,
                        success:function(data, response){
                            $rootScope.showToast(response.Message);
                            if (callback)
                                callback(data);
                        }
                    });
                }

                function beforeOpenDialog(callback){
                    if(callback)
                        callback();
                }

                function openDialog(materialList) {
                    $mddProvider.UseForm('F0102Service', () => {
                        $mdDialog.dialog(
                            'module/moduleF/program/F0102/F0102.html',
                            function (dialog) {
                                return {
                                    //dialog._event['barcode_material_no'].change(dialog.barcode_material_no, {event:$event});
                                    _event: {
                                        'barcode_material_no': {
                                            keyup: (event) => {                                                
                                                dialog.input_material_no(event);                                                
                                            },
                                            change: (barcode_material_no,event) => {
                                                dialog.input_material_no(event);
                                            }
                                        },
                                        'qty':{
                                            click: (event) => {
                                                dialog.input_qty(event)
                                            }
                                        }
                                    },
                                    _fn: {
                                        'Execute': {
                                            click: () => {
                                                dialog.confirm();
                                            }
                                        }
                                    },
                                    css_url: 'module/moduleF/program/F0102/F0102.css',
                                    material_type: material_type, //物料類別
                                    material_no: material_no, //物料編號
                                    barcode_format: barcode_format, //條碼格式
                                    barcode_material_no: '', //條碼掃入物料編號
                                    material_plot_no: 'N/A', //物料批號
                                    qty: '', //物料數量
                                    cordova: window.cordova, //20180828 add by Dustdusk for Android 時不顯示小鍵盤
                                    feed_content: feed_content,//20210507 modify by 德義_林佳諺 for #0086310 設備grid參數
                                    //date: '',
                                    init: function () {
                                        // 20200904 modify by WeiTing for M#77749: 如果上料的物料條碼輸入框使用 mdl-barcode 的話，
                                        // 會跟工作平台的今日生產任務的輸入框的 mdl-barcode 產生衝突，所以這裡只能透過 readonly 的方式，
                                        // 但有部分平板不會自動回車，所以需要在平板狀態時，偵測有輸入值就自動回車。
                                        if (dialog.cordova) {
                                            $interval(function () {
                                                if (dialog.barcode_material_no) {
                                                    $timeout(function () {
                                                        var e = $.Event('keypress');
                                                        e.keyCode = 13; // enter
                                                        $('#input_material').trigger(e);
                                                    });
                                                }
                                            }, 200);
                                        }
                                        $timeout(function () {
                                            $('#barcode_material_no').focus();
                                        },200)
                                    },
                                    input_material_no_callback: function (barcode_material_no) {
                                        if (barcode_material_no != null && barcode_material_no != '') {
                                            // 20201217 add FOR #83902
                                            barcodeAnalysis(barcode_material_no, function (material_plot_no, product_date, Qty) {
                                                if (product_date) {
                                                    product_date = product_date.substring(0, 4) + "/" + product_date.substring(4, 6) + "/" + product_date.substring(6, 8)
                                                }
                                                dialog.material_plot_no = material_plot_no;
                                                dialog.qty = Qty;
                                                dialog.date = product_date ? $filter('date')(product_date, 'yyyy/MM/dd') : "";
                                                $timeout(function () {
                                                    // var qty_element = document.getElementById("input_qty");
                                                    input_qty(qty, dialog);
                                                });
                                            });
                                        }
                                    },
                                    input_material_no: function (event) {                                        
                                        event = event.event;
                                        // 掃入物料編號
                                        if (event != undefined && event.keyCode == 13) {
                                            dialog.input_material_no_callback(dialog.barcode_material_no);
                                        } else if (window.cordova) {
                                            //20180828 add by Dustdusk for Android 時不顯示小鍵盤
                                            if (event.key) {
                                                event.target.value += event.key;
                                            } else {
                                                event.target.value += String.fromCharCode(event.keyCode);
                                            };
                                        }
                                    },
                                    qrcode_material_no: function () {
                                        $rootScope.OpenScanner({
                                            after: function (result) {
                                                dialog.input_material_no_callback(result.text);
                                            },
                                            exception: function () {
                                                //目前裝置無法使用相機
                                                $rootScope.showAlert($filter('translate')('B0214.showAlert.column3'));
                                            },
                                            orientation: 'landscape'
                                        });
                                    },
                                    input_qty: function (event) {
                                        var target = event.currentTarget;
                                        input_qty(target, dialog);
                                    },
                                    focusInputElement: function (id) {
                                        document.getElementById(id).focus();
                                        document.getElementById(id).select();
                                    },
                                    confirm: function () {
                                        beforeFeeding(dialog, function () {
                                            //20210507 modify by 德義_林佳諺 for #0086310 上料(PlugIn == 5)
                                            if (dialog.feed_content != undefined) {
                                                var dis_feed_content = dialog.feed_content;
                                                dis_feed_content.qty = dialog.qty;
                                                dis_feed_content.material_lot_no = dialog.material_plot_no;
                                                dispatchfeedingProcess(dis_feed_content, function () {
                                                    dialog.hide();
                                                    if (options.callback)
                                                        options.callback();
                                                });
                                            } else {
                                                //20210528 modify by 德義_林佳諺 for #0086310 上料(PlugIn != 5 (原上料))
                                                var content = {
                                                    wo_no: options.wo_no,
                                                    op_no: options.op_no,
                                                    machine_no: options.machine_no,
                                                    position_no: options.materialItem.position_no,
                                                    is_need_check_lot: options.materialItem.is_need_check_lot,
                                                    material_no: options.materialItem.material_no,
                                                    substitute_material_no: options.materialItem.substitute_material_no,
                                                    material_plot_no: (dialog.material_plot_no.length == 0) ? 'N/A' : dialog.material_plot_no,
                                                    qty: dialog.qty,
                                                    //20220513 modify by 翰鴻 for M#109626
                                                    put_in_place_type: options.materialItem.put_in_place_type,
                                                    product_date: dialog.date
                                                };
                                                feedingProcess(content, function () {
                                                    dialog.hide();
                                                    if (options.callback)
                                                        options.callback();
                                                });
                                            }
                                        });
                                    },
                                    back: function () {
                                        dialog.hide();
                                    }
                                };
                            }
                        );
                    });
                }

                function input_qty(target, dialog){
                    angular.element(target).addClass('is-focus');
                    $calculater.open(function(num, calcDialog){
                        angular.element(target).removeClass('is-focus');
                        if(+num == 0){
                            $rootScope.showAlert($filter('translate')('F0102.msg.qty_must_gt_zero'));
                        }else{                            
                            calcDialog.hide();
                            dialog.qty = (+num);
                        }
                    },
                    function(calcDialog){
                        angular.element(target).removeClass('is-focus');
                        calcDialog.hide();
                    },
                    {
                        title : $filter('translate')('F0102.calculater-title'),
                        defaultNum : dialog.qty,
                        decimal : true
                    });
                }

                beforeOpenDialog(function(){
                    openDialog();
                });
            };
        }]);
});
